package com.example.module_motorcircle.publish.repository

import com.example.lib_net.api.Api
import com.example.module_motorcircle.publish.model.PublishPostRequestModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import javax.inject.Inject

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/17
 */
class PostPublishRepository  @Inject constructor(){
    @Inject
    lateinit var api: Api


    /**
     * 发布帖子
     */
    fun publishPost(model: PublishPostRequestModel)  = flow {
        emit(api.postPublish(model.toRequestBody()))
    }.flowOn(Dispatchers.IO)

    /**
     * 多文件上传
     */
    fun uploadFiles(files:List<File>) = flow {
        val partList = mutableListOf<MultipartBody.Part>()
        files.forEach { it->
            //file-->RequestBody
            val requestBody = if(it.name.endsWith("png") || it.name.endsWith("jpg"))
                RequestBody.create("image/*".toMediaTypeOrNull(),it)
            else
                RequestBody.create("video/*".toMediaTypeOrNull(),it)
            //RequestBody-->MultipartBody.Part
            val part:MultipartBody.Part = MultipartBody.Part.createFormData("file",it.name,requestBody)
            partList.add(part)
        }
        emit(api.fileUpload(partList))
    }.flowOn(Dispatchers.IO)
}